package com.zhuiyun.educations.api.voide.controller;

import com.zhuiyun.educations.api.voide.entity.Voide;
import com.zhuiyun.educations.api.voide.entity.VoideResult;
import com.zhuiyun.educations.api.voide.service.VoideService;
import com.zhuiyun.educations.common.errorCode.CommonException;
import com.zhuiyun.educations.common.response.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;

/**
 * @ClassName VoideController
 * @Description TODO
 * @Author yuanp
 * @Date 2023/6/23 11:47
 **/
@RestController
@RequestMapping("/voide")
@Slf4j
public class VoideController {

    @Autowired
    private VoideService voideService;

    /**
        * @Author yuanb
        * @Description 检查分片是否存在
        * @Date 2023/6/27 9:11
        * @Return
      //  * @param voide
    */
    @GetMapping("/jiaoChunk")
    public CommonResult checkChunkExist(@RequestParam String identifier,
                                        @RequestParam String chunkNumber,
                                        @RequestParam String filename,
                                        @RequestParam long totalSize,
                                        @RequestParam long chunkSize,
                                        @RequestParam int totalChunks,
                                        @RequestParam String fileType) {
        Voide voide = new Voide();
        voide.setIdentifier(identifier);
        voide.setChunkNumber(chunkNumber);
        voide.setFilename(filename);
        voide.setTotalSize(totalSize);
        voide.setChunkSize(chunkSize);
        voide.setTotalChunks(totalChunks);
        voide.setFileType(fileType);

        log.info("接收到的参数: {}", voide);
        VoideResult voideResult = voideService.checkChunkExist(voide);

        if (voideResult.getUploaded() != null && !voideResult.getUploaded().isEmpty()) {
//            voideResult.setUploaded(voideResult.getMissingChunks());
        }

        return CommonResult.ok(voideResult);
    }


    /**
 * 上传文件分片
 *
 * @param chunkDTO
 * @return
 */
    @PostMapping("/chunk")
    public CommonResult uploadChunk(Voide chunkDTO) {
        try {
            System.out.printf("当前序号=================="+chunkDTO.getChunkNumber());
            voideService.uploadChunk(chunkDTO);
            return CommonResult.ok(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return CommonResult.error(e.getMessage());
        }
    }

    /**
     * 请求合并文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("/merge")
    public CommonResult mergeChunks(Voide chunkDTO)  {
        try {

            return CommonResult.ok(voideService.mergeChunk(chunkDTO));
        } catch (Exception e) {
            return CommonResult.error(e);
        }
    }



}
